package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.entity.RoleExample;
import com.atguigu.crowd.mapper.RoleMapper;
import com.atguigu.crowd.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * role的业务接口实现类
 *
 * @author wmb
 *
 * @since 2021-1-21
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    private Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    @Qualifier("roleMapper")
    private RoleMapper roleMapper;

    /**
     * 分页查询角色
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     *
     * @return
     */
    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
        // 1.开启分页功能
        PageHelper.startPage(pageNum, pageSize);

        // 2.执行查询
        try {
            List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);
            logger.info("roleList: " + roleList);
            // 3.封装为pageInfo对象返回
            return new PageInfo<>(roleList);
        } catch (Exception e) {
            logger.error("role分页查询失败，错误原因为: " + e.getMessage());
            return null;
        }
    }

    /**
     * 保存Role
     *
     * @param role
     */
    @Override
    public void saveRole(Role role) {
        roleMapper.insert(role);
    }

    /**
     * 更新Role
     *
     * @param role
     */
    @Override
    public void updateRole(Role role) {
       roleMapper.updateByPrimaryKey(role);
    }

    /**
     * 批量删除role
     *
     * @param roleIdList
     */
    @Override
    public void removeRole(List<Integer> roleIdList) {
        RoleExample example = new RoleExample();

        RoleExample.Criteria criteria = example.createCriteria();

        // delete from t_role  where id in (5, 8, 12)
        criteria.andIdIn(roleIdList);

        roleMapper.deleteByExample(example);
    }

    /**
     * 根据adminId获取用户已获得的角色
     *
     * @param adminId
     *
     * @return
     */
    @Override
    public List<Role> getAssignedRole(Integer adminId) {
        return roleMapper.selectAssignedRole(adminId);
    }

    /**
     * 根据adminId获取用户未获得的角色
     *
     * @param adminId
     *
     * @return
     */
    @Override
    public List<Role> getUnAssignedRole(Integer adminId) {
        return roleMapper.selectUnAssignedRole(adminId);
    }
}
